package com.ihr360.job.config;

import com.ihr360.job.core.config.JobBuilderFactory;
import com.ihr360.job.core.config.StepBuilderFactory;
import com.ihr360.job.core.lanuch.JobLauncher;
import com.ihr360.job.core.lanuch.support.SimpleJobLauncher;
import com.ihr360.job.core.repository.JobRepository;
import com.ihr360.job.core.repository.support.JobRepositoryFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
public class BatchConfig {
    private static final Logger logger = LoggerFactory.getLogger(BatchConfig.class);
    @Autowired
    private DataSource dataSource;

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Autowired
    private PlatformTransactionManager transactionManager;

    private JobRepository jobRepository;

    private JobLauncher jobLauncher;

    private static ThreadPoolTaskExecutor executor;

    @Bean
    JobBuilderFactory jobBuilderFactory() {
        return new JobBuilderFactory(this.getJobRepository());
    }

    @Bean
    StepBuilderFactory stepBuilderFactory() {
        return new StepBuilderFactory(this.getJobRepository(), transactionManager);
    }

    @Bean
    public JobRepository jobRepository() {
        return this.jobRepository;
    }

    @Bean
    public JobLauncher jobLauncher() {
        return this.jobLauncher;
    }

    public static ThreadPoolTaskExecutor asyncExecutor() {
        if (executor == null) {
            executor=new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(200);
            executor.setMaxPoolSize(200);
            executor.setQueueCapacity(0);
            executor.setThreadNamePrefix("ihr360-JE-asyncExecutor-");

            // 自定义拒绝策略
        /*executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                //........
            }
        });*/
            executor.initialize();
        }

        return executor;
    }


    @PostConstruct
    public void initialize() {
        try {
            this.jobRepository = createJobRepository();
            this.jobLauncher = createJobLauncher();
        } catch (Exception ex) {
            throw new IllegalStateException("Unable to initialize Spring Batch", ex);
        }
    }

    private JobLauncher createJobLauncher() throws Exception {
        SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
        jobLauncher.setJobRepository(getJobRepository());
        jobLauncher.setTaskExecutor(asyncExecutor());
        jobLauncher.afterPropertiesSet();
        return jobLauncher;
    }


    private JobRepository createJobRepository() throws Exception {
        JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
        factory.setDataSource(this.dataSource);
        if (this.entityManagerFactory != null) {
            logger.warn(
                    "JPA does not support custom isolation levels, so locks may not be taken when launching Jobs");
            factory.setIsolationLevelForCreate("ISOLATION_DEFAULT");
        }

        factory.setTransactionManager(transactionManager);
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    private JobRepository getJobRepository() {
        return this.jobRepository;
    }


    public PlatformTransactionManager transactionManager() {
        return createTransactionManager();
    }


    protected PlatformTransactionManager createTransactionManager() {
        PlatformTransactionManager transactionManager = createAppropriateTransactionManager();
        return transactionManager;
    }

    private PlatformTransactionManager createAppropriateTransactionManager() {
        if (this.entityManagerFactory != null) {
            return new JpaTransactionManager(this.entityManagerFactory);
        }
        return new DataSourceTransactionManager(this.dataSource);
    }
}